package com.wehealth.three.lib_connect.utils;


import android.annotation.SuppressLint;
import android.content.Context;


import com.wehealth.three.lib_connect.data.ResultPassHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class ECGDataUtil {

    public static class ECGDataResultHelper {
        /**
         * code:name
         */
        private Map<String, String> classfy = new HashMap<String, String>();
        /**
         * code:name
         */
        private Map<String, String> result = new HashMap<String, String>();
        private int diagnosisType = -1;

        public Map<String, String> getClassfy() {
            return classfy;
        }

        public void setClassfy(Map<String, String> classfy) {
            this.classfy = classfy;
        }

        public Map<String, String> getResult() {
            return result;
        }

        public void setResult(Map<String, String> result) {
            this.result = result;
        }

        public int getDiagnosisType() {
            return diagnosisType;
        }

        public void setDiagnosisType(int diagnosisType) {
            this.diagnosisType = diagnosisType;
        }
    }

    /****
     *  分析结果的字符串转化为对象
     * @param result
     * @return
     * @throws Exception
     */
    public static ECGDataResultHelper decodeEcgResult(String result) throws Exception {
        JSONObject obj;
        try {
            obj = new JSONObject(result);
        } catch (Exception ex) {
            throw new Exception("Not Json Format");
        }

        ECGDataResultHelper helper = new ECGDataResultHelper();

        boolean hasClassfy = obj.has("classfy");
        if (hasClassfy) {
            JSONArray classArray = obj.getJSONArray("classfy");
            for (int i = 0; i < classArray.length(); i++) {
                JSONObject element = classArray.getJSONObject(i);
                helper.getClassfy().put(element.getString("code"), element.getString("name"));
            }
        }

        boolean hasResult = obj.has("result");
        if (hasResult) {
            JSONArray resArray = obj.getJSONArray("result");
            for (int i = 0; i < resArray.length(); i++) {
                JSONObject element = resArray.getJSONObject(i);
                helper.getResult().put(element.getString("code"), element.getString("name"));
            }
        }
        boolean hasType = obj.has("diagnosisType");
        if (hasType)
            helper.setDiagnosisType(obj.getInt("diagnosisType"));

        return helper;
    }

    /****
     * 将分析结果的对象转化为字符串
     * @param helper
     * @return
     */
    public static String encodeEcgResult(ECGDataResultHelper helper) {
        JSONObject obj = null;
        try {
            obj = new JSONObject();
            if (!helper.getClassfy().isEmpty()) {
                JSONArray array = new JSONArray();
                obj.put("classfy", array);

                Map<String, String> classfy = helper.getClassfy();
                for (String code : classfy.keySet()) {
                    JSONObject element = new JSONObject();
                    array.put(element);

                    String name = classfy.get(code);
                    element.put("code", code);
                    element.put("name", name);
                }
            }

            if (!helper.getResult().isEmpty()) {
                JSONArray array = new JSONArray();
                obj.put("result", array);

                Map<String, String> result = helper.getResult();
                for (String code : result.keySet()) {
                    JSONObject element = new JSONObject();
                    array.put(element);

                    String name = result.get(code);
                    element.put("code", code);
                    element.put("name", name);
                }
            }
            if (helper.getDiagnosisType() != -1) {
                obj.put("diagnosisType", helper.getDiagnosisType());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return obj.toString();
    }

    /**
     * 将自动分析返回的json结果解析程字符串
     **/
    public static String getClassByJson(String classStr) {
        String classRes = "";
        try {
            Iterator<Entry<String, String>> itc = decodeEcgResult(classStr).getClassfy().entrySet().iterator();
            while (itc.hasNext()) {
                Entry<String, String> entry = itc.next();
                classRes += entry.getValue() + " ";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return classRes;
        }
        return classRes;
    }

    /**
     * 将心电分析结论的Json格式解析
     **/
    public static String getResultByJson(String resultStr) {
        String result = "";
        try {
            Iterator<Entry<String, String>> itc = decodeEcgResult(resultStr).getResult().entrySet().iterator();
            while (itc.hasNext()) {
                Entry<String, String> entry = itc.next();
                result += entry.getValue() + " ";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    public static String str2Json(String classfy, String result) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("classfy", classfy);
            jsonObject.put("result", result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    public static ResultPassHelper json2Obj(String json) {
        ResultPassHelper rph = new ResultPassHelper();
        rph.setProps("分析失败", "分析失败");
        try {
            JSONObject jsonObject = new JSONObject(json);
            if (jsonObject.has("classfy")) {
                String name = jsonObject.getString("classfy");
                rph.setName(name);
            }
            if (jsonObject.has("result")) {
                String value = jsonObject.getString("result");
                rph.setValue(value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return rph;
    }

    /**
     * 获取结论的分级建议
     *
     * @param context
     * @param
     * @return ResuPassHelper name：级别；value：建议
     */
    public static ResultPassHelper obtainWarn2LevelMap(Context context, String result) {
        ResultPassHelper rph = new ResultPassHelper();
        InputStream is = null;
        boolean is_replace = false;
        if (result.contains("ST & T异常")) {
            result = result.replace("ST & T异常", "");
            is_replace = true;
        }
        try {
            is = context.getAssets().open("ecgdata_th2_resultadvice.xml");
            Map<String, String> map = parser2LevelAdvice(result, is);
            if (map == null || map.isEmpty()) {
                return null;
            }
            if (map.containsKey("三")) {//含有危险级别最高
                rph.setName("三");
                return rph;
            }
            if (map.containsKey("二")) {//含有危险级别次之
                rph.setName("二");
                return rph;
            }
            if (is_replace) {//不含有危险级别次之，但被替换了结论
                rph.setName("二");
                return rph;
            }
            if (map.containsKey("一")) {//正常心电图
                rph.setName("一");
                return rph;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 解析文件
     *
     * @param result
     * @param is
     * @return
     */
    @SuppressLint("UseSparseArrays")
    public static Map<String, String> parser2LevelAdvice(String result, InputStream is) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            XmlPullParserFactory pullFactory = XmlPullParserFactory.newInstance();
            XmlPullParser pullParser = pullFactory.newPullParser();
            pullParser.setInput(is, "UTF-8");
            int eventType = pullParser.getEventType();
            while (XmlPullParser.END_DOCUMENT != eventType) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        String[] r = result.split(" ");
                        for (int i = 0; i < r.length; i++) {
                            String name = pullParser.getAttributeValue(null, "name");
                            String level = pullParser.getAttributeValue(null, "level");
                            if (r[i].equals(name)) {
                                String strLevel = level;
                                map.put(strLevel, "");
                                break;
                            }
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                    case XmlPullParser.END_DOCUMENT:
                        break;
                    default:
                        break;
                }
                eventType = pullParser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 获取结论的分级建议
     *
     * @param context
     * @param result
     * @return 级别建议
     */
    public static ResultPassHelper obtainWarnLevelMap(Context context, String result) {
        ResultPassHelper rph = new ResultPassHelper();
        InputStream is = null;
        boolean is_replace = false;
        if (result.contains("ST & T异常")) {
            result = result.replace("ST & T异常", "");
            is_replace = true;
        }
        try {
            is = context.getAssets().open("ecgdata_resultadvice.xml");
            Map<String, String> map = parserLevelAdvice(result, is);
            if (map == null || map.isEmpty()) {
                return null;
            }
            if (map.containsKey("三")) {//含有危险级别最高
                rph.setName("三");
                return rph;
            }
            if (map.containsKey("二")) {//含有危险级别次之
                rph.setName("二");
                return rph;
            }
            if (is_replace) {//不含有危险级别次之，但被替换了结论
                rph.setName("二");
                return rph;
            }
            if (map.containsKey("一")) {//正常心电图
                rph.setName("一");
                return rph;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 解析文件
     *
     * @param result
     * @param is
     * @return
     */
    @SuppressLint("UseSparseArrays")
    public static Map<String, String> parserLevelAdvice(String result, InputStream is) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            XmlPullParserFactory pullFactory = XmlPullParserFactory.newInstance();
            XmlPullParser pullParser = pullFactory.newPullParser();
            pullParser.setInput(is, "UTF-8");
            int eventType = pullParser.getEventType();
            while (XmlPullParser.END_DOCUMENT != eventType) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        String[] r = result.split(" ");
                        for (int i = 0; i < r.length; i++) {
                            String name = pullParser.getAttributeValue(null, "name");
                            String level = pullParser.getAttributeValue(null, "level");
                            if (r[i].equals(name)) {
                                String strLevel = level;
                                map.put(strLevel, "");
                                break;
                            }
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                    case XmlPullParser.END_DOCUMENT:
                        break;
                    default:
                        break;
                }
                eventType = pullParser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }


}
